﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using wenku8.Entity;
using wenku8.MyEventArgs;
using wenku8.Parser;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板

namespace wenku8.Xamls
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class BookDetalsPage : Page
    {
        internal string readLinkage;
        internal List<object> parameters;
        private static string localTitle;
        private int pageNum;
        private BookItem Bookitem { get; set; }
        private ObservableCollection<BookIndex> BookIndexes { get; set; }
        private ObservableCollection<Comment> comments;

        private static ScrollViewer ContentScrollViewer;

        public BookDetalsPage()
        {
            this.InitializeComponent();
            pageNum = 1;
            ContentScrollViewer = contentScrollViewer;
            parameters = new List<object>();
            BookIndexes = new ObservableCollection<BookIndex>();
            comments = new ObservableCollection<Comment>();

            MainPage.PostCommentEvent += PostCommentAsync;
            MainPage.ReturnTopEvent += ReturnTop;
        }

        private void ReturnTop(object sender, EventArgs e)
        {
            if (this.Frame != null)
                contentScrollViewer?.ChangeView(null, 0, null);
        }

        private async void PostCommentAsync(object sender, EventArgs e)
        {
            var commentEventArgs = e as CommentEventArgs;
            string comment = commentEventArgs.Comment;

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Encoding gbk = Encoding.GetEncoding("GBK");
            Encoding gb2312 = Encoding.GetEncoding("GB2312");

            comment = gbk.GetString(gb2312.GetBytes(comment));

            var parameters = new List<KeyValuePair<string, string>>() {
                new KeyValuePair<string, string>("pcontent",comment),
            };
            var suri = $"https://www.wenku8.net/modules/article/reviews.php?aid={Bookitem.BID}";
            var htmlPage = await CommentParser.PostCommentAsync(suri, parameters);
            if (htmlPage != null) {
                pageNum = 1;
                comments?.Clear();
                await GetCommentsAsync(htmlPage).ContinueWith(async antecedent =>
                {
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { MainPage.PopMessageDialog("发表成功！"); });
                });
            }
            else
                MainPage.PopMessageDialog("评论失败！");
        }

        // 导航到本页面时触发
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.New) {
                MainPage.DisableReturnTopButton();
                comments.Clear();
                Bookitem = e.Parameter as BookItem;
                bookDetailsGrid.DataContext = Bookitem;
                localTitle = MainPage.TitleTextBlock.Text = Bookitem.Title;
                var htmlPage = await HTMLParser.GetHtmlString(Bookitem.Interlinkage);// "https://www.wenku8.net/book/1143.htm"
                if (htmlPage == null) {
                    MainPage.PopMessageDialog("网络或服务器故障！");
                    return;
                }
                var htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(htmlPage);
                var contentNode = htmlDoc.GetElementbyId("content");
                var tables = contentNode.SelectNodes("//table");
                var detailsTable = tables[2];
                var similarTable = tables[3];
                var commentTable = tables[4];

                // 介绍
                var summary = contentNode.ChildNodes[1].ChildNodes[7].ChildNodes[1].ChildNodes[3].ChildNodes[13].InnerText;
                readLinkage = contentNode.ChildNodes[1].ChildNodes[11].ChildNodes[1].ChildNodes[1].ChildNodes[1].ChildNodes[3].ChildNodes[0].Attributes["href"].Value;
                Bookitem.Summary = summary.Replace("&nbsp;", " ");
                Bookitem.ReadLinkage = readLinkage;

                // 评论
                var tempComments = new ObservableCollection<Comment>();
                var trNodes = commentTable.SelectNodes(commentTable.XPath + "//tr");
                trNodes.RemoveAt(2);
                trNodes.RemoveAt(1);
                trNodes.RemoveAt(0);
                await CommentParser.GetCommentsAsync(tempComments, trNodes);
                commentListView.ItemsSource = tempComments;

                try {
                    var localFolder = ApplicationData.Current.LocalCacheFolder;
                    var file = await localFolder.GetFileAsync("collectedNovels.txt");
                    var collectedNovels = await FileIO.ReadTextAsync(file);
                    if (collectedNovels.Contains(Bookitem.BID)) {
                        CollectButton.Content = "取消收藏";
                    }
                    else {
                        CollectButton.Content = "添加收藏";
                    }
                }
                catch (Exception) {
                    CollectButton.Content = "添加收藏";
                }

                summaryTextBlock.Text = Bookitem.Summary;

                htmlPage = await HTMLParser.GetHtmlString(Bookitem.ReadLinkage);
                if (htmlPage == null) {
                    MainPage.PopMessageDialog("已取消收藏！");
                }
                else {
                    BookIndexes.Clear();
                    BookIndexParser.GetBookIndexes(htmlPage, BookIndexes);
                    MainPage.DisableProgressRing();
                }
            }
            else if (e.NavigationMode == NavigationMode.Back) {
                MainPage.TitleTextBlock.Text = localTitle;
                MainPage.DisableProgressRing();
            }

            #region test code
            //var list = new List<Comment>()
            //{
            //    new Comment()
            //    {
            //         HeadImage=new BitmapImage(new Uri("https://www.wenku8.net/files/system/avatar/369/369747.jpg")),
            //         Content="士织spirit",
            //         Date="09-07 17:01",
            //         UserName="xsevzk",
            //         ReplayCount="116",
            //         ViewCount="381"
            //    }
            //};
            //commentListView.ItemsSource = list;
            #endregion
        }

        private void VolumnIndexGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            parameters.Clear();
            var bookIndex = (BookIndex)e.ClickedItem;
            if (bookIndex != null) {
                parameters.Add(bookIndex);
                parameters.Add(readLinkage);
                MainPage.EnableProgressRing();
                this.Frame.Navigate(typeof(ChapterIndexPage), parameters);
            }
        }

        // 收藏按钮的点击处理
        private async void CollectButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            if ((sender as Button).Content.Equals("添加收藏")) {
                await HTMLParser.GetHtmlString(BaseURIs.collectNovelURI + Bookitem.BID);
                MainPage.PopMessageDialog("收藏成功！");
                CollectButton.Content = "取消收藏";
            }
            else {
                await HTMLParser.GetHtmlString(BaseURIs.deleteNovelURI + Bookitem.DelID);
                MainPage.PopMessageDialog("已取消收藏！");
                CollectButton.Content = "添加收藏";
            }
        }

        // 推荐按钮的点击处理
        private async void RecommendButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            var htmlPage = await HTMLParser.GetHtmlString(BaseURIs.voteNovelURI + Bookitem.BID);
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(htmlPage);
            foreach (var node in htmlDoc.DocumentNode.Descendants()) {
                try {
                    if (node.Attributes["class"].Value == "blockcontent") {
                        MainPage.PopMessageDialog(node.InnerText);
                        break;
                    }
                }
                catch (Exception) {
                    // 当节点没有属性时， node.Attributes["class"]会抛出异常，不做处理，继续处理下一个节点
                }
            }
        }

        // 滚动事件处理。滚动到底部时加载下一页的评论
        private bool isScrolled = true;
        private async void ContentScrollViewer_ViewChangedAsync(object sender, ScrollViewerViewChangedEventArgs e)
        {
            if (contentScrollViewer.VerticalOffset > contentScrollViewer.ScrollableHeight - 10 && isScrolled) {
                isScrolled = false;

                var uri = $"https://www.wenku8.net/modules/article/reviews.php?aid={Bookitem.BID}&type=all&page={pageNum++}";
                var htmlPage = await HTMLParser.GetHtmlString(uri);
                await GetCommentsAsync(htmlPage).ContinueWith(antecedent => { isScrolled = true; });
            }
            if (contentScrollViewer.VerticalOffset > contentScrollViewer.ActualHeight)
                MainPage.EnableReturnTopButton();
            else
                MainPage.DisableReturnTopButton();
        }

        private async Task GetCommentsAsync(string htmlPage)
        {
            var htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(htmlPage);
            var contentNode = htmlDoc.GetElementbyId("content");
            var commentTable = contentNode.SelectSingleNode(contentNode.XPath + "/table[@class=\"grid\"]");
            if (commentTable == null)
                return;
            var trNodes = commentTable.SelectNodes(commentTable.XPath + "//tr");
            trNodes.RemoveAt(0);
            commentListView.ItemsSource = comments;
            await CommentParser.GetCommentsAsync(comments, trNodes);
        }

        private void CommentListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem is Comment) {
                this.Frame.Navigate(typeof(RepliesPage), e.ClickedItem);
                MainPage.EnableProgressRing();
            }
        }
    }
}
